var app = getApp();
var playTimeInterval;
var recordTimeInterval;

var receiving= false,
  recording= false,
    playing= false,
      hasRecord= false,
        recordTime= 0,
          playTime= 0,
            formatedRecordTime= '00:00:00',
              formatedPlayTime= '00:00:00';

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function getDateStr(AddDayCount) {
  var dd = new Date();
  dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;//获取当前月份的日期
  var d = dd.getDate();
  return dateformat((y + "-" + m + "-" + d),'yyyy-MM-dd');
}
function dateformat(datetime, formatStr) {
  if (typeof datetime == "object") {
    dateObjectformat(datetime, formatStr);
    return false;
  };
  var str = formatStr, datestr = [], timestr = [];

  var datetime = datetime.split(' ');
  if (datetime[0]) {
    datestr = datetime[0].split('-');
  }
  if (datetime[1]) {
    timestr = datetime[1].split(':');
  }

  var year = Number(datestr[0]);
  var syear = Number(datestr[0]);
  var month = Number(datestr[1]);
  var smonth = Number(datestr[1]);
  var date = Number(datestr[2]);
  var sdate = Number(datestr[2]);
  var hours = Number(timestr[0]);
  var shours = Number(timestr[0]);
  var minutes = Number(timestr[1]);
  var sminutes = Number(timestr[1]);
  var seconds = Number(timestr[2]);
  var sseconds = Number(timestr[2]);

  str = str.replace(/yyyy|YYYY|yy|YY/, year);
  //str=str.replace(/yy|YY/,(syear % 100)>9?(syear % 100):"0" + (syear % 100));
  str = str.replace(/MM/, month > 9 ? month : "0" + month);
  str = str.replace(/M/g, smonth);
  str = str.replace(/dd|DD/, date > 9 ? date : "0" + date);
  str = str.replace(/d|D/g, sdate);
  str = str.replace(/hh|HH/, hours > 9 ? hours : "0" + hours);
  str = str.replace(/h|H/g, shours);
  str = str.replace(/mm/, minutes > 9 ? minutes : "0" + minutes);
  str = str.replace(/m/g, sminutes);
  str = str.replace(/ss|SS/, seconds > 9 ? seconds : "0" + seconds);
  str = str.replace(/s|S/g, sseconds);
  return str; var str = formatStr;

  var datetime = datetime.split(' ');
  var datestr = datetime[0].split('-');
  var timestr = datetime[1].split(':');

  var year = Number(datestr[0]);
  var syear = Number(datestr[0]);
  var month = Number(datestr[1]);
  var smonth = Number(datestr[1]);
  var date = Number(datestr[2]);
  var sdate = Number(datestr[2]);
  var hours = Number(timestr[0]);
  var shours = Number(timestr[0]);
  var minutes = Number(timestr[1]);
  var sminutes = Number(timestr[1]);
  var seconds = Number(timestr[2]);
  var sseconds = Number(timestr[2]);

  str = str.replace(/yyyy|YYYY/, year);
  str = str.replace(/yy|YY/, (syear % 100) > 9 ? (syear % 100) : "0" + (syear % 100));
  str = str.replace(/MM/, month > 9 ? month : "0" + month);
  str = str.replace(/M/g, smonth);
  str = str.replace(/dd|DD/, date > 9 ? date : "0" + date);
  str = str.replace(/d|D/g, sdate);
  str = str.replace(/hh|HH/, hours > 9 ? hours : "0" + hours);
  str = str.replace(/h|H/g, shours);
  str = str.replace(/mm/, minutes > 9 ? minutes : "0" + minutes);
  str = str.replace(/m/g, sminutes);
  str = str.replace(/ss|SS/, seconds > 9 ? seconds : "0" + seconds);
  str = str.replace(/s|S/g, sseconds);
  return str;
}
function dateObjectformat(date, formatStr) {
  var str = formatStr;
  str = str.replace(/yyyy|YYYY/, date.getFullYear());
  str = str.replace(/yy|YY/, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : "0" + (date.getYear() % 100));
  var _m = date.getMonth() + 1;
  str = str.replace(/MM/, _m > 9 ? _m : "0" + _m);
  str = str.replace(/M/g, _m);
  str = str.replace(/dd|DD/, date.getDate() > 9 ? date.getDate().toString() : "0" + date.getDate());
  str = str.replace(/d|D/g, date.getDate());
  str = str.replace(/hh|HH/, date.getHours() > 9 ? date.getHours().toString() : "0" + date.getHours());
  str = str.replace(/h|H/g, date.getHours());
  str = str.replace(/mm/, date.getMinutes() > 9 ? date.getMinutes().toString() : "0" + date.getMinutes());
  str = str.replace(/m/g, date.getMinutes());
  str = str.replace(/ss|SS/, date.getSeconds() > 9 ? date.getSeconds().toString() : "0" + date.getSeconds());
  str = str.replace(/s|S/g, date.getSeconds());
  return str;
}
function getData(router,params,callback){
  var url = app.server + router;
  if (router.indexOf("/")>-1){
    url = app.server + router;
  }
  var header = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
  if(app.globalData.token){
    header['AUTHORIZATION'] = app.globalData.token;
  }
  wx.request({
    url: url,
    method: 'GET',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
function postData(router, params, callback) {
  var url = app.server + router;
  if (router.indexOf("/") > -1) {
    url = app.server + router;
  }
  var header = {
    'content-type': 'application/json; charset=UTF-8'
  }
  if(app.globalData.token){
    header['AUTHORIZATION'] = app.globalData.token;
  }
  wx.request({
    url: url,
    method: 'POST',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
function putData(router, params, callback) {
  var url = app.server + router;
  if (router.indexOf("/") > -1) {
    url = app.server + router;
  }
  var header = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
  if(app.globalData.token){
    header['AUTHORIZATION'] = app.globalData.token;
  }
  wx.request({
    url: url,
    method: 'PUT',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
function deleteData(router, params, callback) {
  var url = app.server + router;
  if (router.indexOf("/") > -1) {
    url = app.server + router;
  }
  var header = {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'AUTHORIZATION':app.globalData.token
    }
  wx.request({
    url: url,
    method: 'DELETE',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
//////////

function getData2(router,params,callback){
  var url = app.server2 + '/wechat/wxapplet/' + router;
  if (router.indexOf("/")>-1){
    url = app.server2 + router;
  }
  var header = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
  if(app.globalData.token){
    header['AUTHORIZATION'] = app.globalData.token;
  }
  wx.request({
    url: url,
    method: 'GET',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
function postData2(router, params, callback) {
  var url = app.server2 + router;
  if (router.indexOf("/") > -1) {
    url = app.server2 + router;
  }
  var header = {
    'content-type': 'application/json; charset=UTF-8'
  }
  if(app.globalData.token){
    header['AUTHORIZATION'] = app.globalData.token;
  }
  wx.request({
    url: url,
    method: 'POST',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
function putData2(router, params, callback) {
  var url = app.server2 + router;
  if (router.indexOf("/") > -1) {
    url = app.server2 + router;
  }
  var header = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
  if(app.globalData.token){
    header['AUTHORIZATION'] = app.globalData.token;
  }
  wx.request({
    url: url,
    method: 'PUT',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
function deleteData2(router, params, callback) {
  var url = app.server2 + router;
  if (router.indexOf("/") > -1) {
    url = app.server2 + router;
  }
  var header = {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'AUTHORIZATION':app.globalData.token
    }
  wx.request({
    url: url,
    method: 'DELETE',
    header: header,
    data: params,
    success: function (res) {
      if (callback) {
        callback(res, null)
      }
    },
    fail: function (error) {
      if (callback) {
        callback(null, error)
      }
    }
  });
}
//(sender,receiver,shop,order_id,message,url)
function sendMessage(params, callback) {
  var header = {
    'content-type': 'application/json',
    'AUTHORIZATION':app.globalData.token
  }
  wx.request({
    url: app.server + '/wechat/wxapplet/sendMessage',
    method: 'POST',
    header: header,
    data: {data:params},
    success: function (res) {
      if (callback) {
        callback(res)
      }
    },
    fail: function (error) {
      console.log(error);
    }
  });
}

function startTouchRecord(e) {
  this.startRecord();
}
function stopTouchRecord (e) {
  wx.stopRecord();
  wx.hideToast();
}
function startRecord () {
  var that = this
  this.setData({ recording: true })
  wx.showToast({
    title: '语音记录中',
    icon: 'loading',
    duration: 999999999,
    mask: true
  })
  recordTimeInterval = setInterval(function () {
    var recordTime = recordTime += 1
    that.setData({
      formatedRecordTime: speechFormatTime(recordTime),
      recordTime: recordTime
    })
  }, 1000)
  wx.startRecord({
    success: function (res) {
      that.setData({
        hasRecord: true,
        tempFilePath: res.tempFilePath,
        formatedPlayTime: speechFormatTime(playTime)
      });
      wx.showToast({
        title: '语音识别中',
        icon: 'loading',
        duration: 999999999,
        mask: true
      })
      wx.uploadFile({
        url: app.server + '/wechat/wxapplet/voice',
        header:{
          'Authorization': app.globalData.token
        },
        filePath: res.tempFilePath,
        name: 'file',
        header: {'Cookie':app.globalData.cookie}, // 设置请求的 header
        formData: {
          'id': orderId,
          'shop': shop,
          'object': 'driver',
          'time': formatedRecordTime
        }, // HTTP 请求中其他额外的 form data
        success: function (res) {
          // success
          var data = JSON.parse(res.data);
          if (data.success) {
            chatList.push({
              "type": "record", "url": app.server + data.file, "time": formatedRecordTime
            });
            that.setData({
              chatList: chatList
            });
          };
          //wx.hideToast()
        },
        fail: function (err) {
          // fail
          console.log(err);
        },
        complete: function () {
          // complete
        }
      })
    },
    complete: function () {
      that.setData({ recording: false })
      clearInterval(recordTimeInterval)
    }
  })
}
function playVoice (e) {
  console.log(e.currentTarget.dataset.url)
  var that = this;
  if (that.data.playing) {
    that.stopVoice();
    return false;
  }
  wx.playBackgroundAudio({
    dataUrl: e.currentTarget.dataset.url,
    title: '',
    coverImgUrl: ''
  })
}
function stopRecord () {
  wx.stopRecord()
}
function stopVoice () {
  clearInterval(playTimeInterval)
  this.setData({
    playing: false,
    formatedPlayTime: speechFormatTime(0),
    playTime: 0
  })
  wx.stopVoice()
}
function speechRecognition (callback) {
  var that = this;
  wx.showToast({
    title: '语音记录中',
    icon: 'loading',
    duration: 999999999//,
    //mask: true
  })
  recordTimeInterval = setInterval(function () {
    recordTime = recordTime += 1
    formatedRecordTime = speechFormatTime(recordTime)
  }, 1000)
  wx.startRecord({
    success: function (res) {
      wx.showToast({
        title: '语音识别中',
        icon: 'loading',
        duration: 999999999//,
        //mask: true
      })
      wx.uploadFile({
        url: app.server + '/wechat/wxapplet/voice',
        header:{
          'Authorization': app.globalData.token
        },
        filePath: res.tempFilePath,
        name: 'file',
        header: {'Cookie':app.globalData.cookie}, // 设置请求的 header
        formData: {
          'recognition': true
        }, // HTTP 请求中其他额外的 form data
        success: function (res) {
          var data = JSON.parse(res.data);
          if (data.success) {
            callback(data.data);
          } else {
            callback(false);
          };
          //wx.hideToast()
        },
        fail: function (err) {
          // fail
          console.log(err);
        },
        complete: function () {
          // complete
        }
      })
    },
    complete: function () {
      clearInterval(recordTimeInterval);
      recordTime = 0, formatedRecordTime = '00:00:00';
    }
  })
}
function speechFormatTime (time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  var hour = parseInt(time / 3600)
  time = time % 3600
  var minute = parseInt(time / 60)
  time = time % 60
  var second = time

  return ([minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}
/////////////////////////////////////////////
function setPointAttr(that,type, warehouse, shop){
  var delivery_point, point_name = '配送点', point_id = '';
  if (type == 'warehouse') {
    delivery_point = 'W' + warehouse;
    point_name = '发货点';
    point_id = warehouse;
  } else {
    delivery_point = 'S' + shop;
    point_name = '收货点';
    point_id = shop;
  }
  var currentPointAttr = {
    type: type,
    delivery_point: delivery_point,
    point_name: point_name,
    point_id: point_id
  };
  that.setData({
    currentPointAttr: currentPointAttr
  });
  return currentPointAttr;
}
///小时转为时间：XX时XX分/////////////////////
function hourToTime(duration){
  var duration = duration / 60 / 60;
  var hour = Math.floor(duration);
  var minute = ((duration - hour)*60).toFixed(0);
  return { hour: hour, minute: minute}
}

function vehicleTrace(id) {
  wx.getNetworkType({
    success: function (res) {
      // 返回网络类型, 有效值：
      // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
      var networkType = res.networkType
      if (networkType != "wifi") {
        wx.showModal({
          title: '小冷通TMS-行车轨迹',
          content: '您的网络不是wifi，即将打开的行车轨迹页面轨迹数据量比较大，可能会产生比较大的流量。请问继续访问吗？',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/index/web?url=' + app.server+'/webview/monitor/order/' + id
              });
            } else if (res.cancel) {

            }
          }
        })
      } else {
        wx.navigateTo({
          url: '/pages/index/web?url=' + app.server +'/webview/monitor/order/' + id
        });
      }
    }
  })
}

function vehicleTraceWithIotbox(iot_box, start_time, end_time) {
  var data = iot_box + '_' + start_time + '_' + end_time
  wx.getNetworkType({
    success: function (res) {
      // 返回网络类型, 有效值：
      // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
      var networkType = res.networkType
      if (networkType != "wifi") {
        wx.showModal({
          title: '小冷通TMS-行车轨迹',
          content: '您的网络不是wifi，即将打开的行车轨迹页面轨迹数据量比较大，可能会产生比较大的流量。请问继续访问吗？',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/index/web?url=' + app.server +'/webview/monitor/vehicle/' + data
              });
            } else if (res.cancel) {

            }
          }
        })
      } else {
        wx.navigateTo({
          url: '/pages/index/web?url=' + app.server +'/webview/monitor/vehicle/' + data
        });
      }
    }
  })
}

function gpsTransform(lat, lon) {
  var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
  var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
  var dLat = transformLat(lon - 105.0, lat - 35.0);
  var dLon = transformLon(lon - 105.0, lat - 35.0);
  var radLat = lat / 180.0 * Math.PI;
  var magic = Math.sin(radLat);
  magic = 1 - ee * magic * magic;
  var sqrtMagic = Math.sqrt(magic);
  dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
  dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI);
  return { 'lat': lat + dLat, 'lon': lon + dLon };
};
function transformLat(x, y) {
  var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
  return ret;
};
function transformLon(x, y) {
  var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
  return ret;
};
function toRad(d) { return d * Math.PI / 180; }
function getGpsDisance(lat1, lng1, lat2, lng2) {
  // var R = 6378245.0; // metres6378137
  // var φ1 = toRad(lat1);
  // var φ2 = toRad(lat2);
  // var Δφ = toRad(lat2-lat1);
  // var Δλ = toRad(lng2-lng1);
  //
  // var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
  //     Math.cos(φ1) * Math.cos(φ2) *
  //     Math.sin(Δλ/2) * Math.sin(Δλ/2);
  // var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  //
  // var d = R * c;
  // return d;

  var R = 6378245.0; // metres6378137
  var radLat1 = toRad(lat1);
  var radLat2 = toRad(lat2);
  var a = radLat1 - radLat2;
  var b = toRad(lng1) - toRad(lng2);

  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * R;
  //s = Math.Round(s * 10000) / 10000;
  return (s || 0);
}

function driverScan(){
  wx.scanCode({
    onlyFromCamera: true,
    success: function (res) {
      console.log(res)
      var code = res.result;
      postData("qrcodeAnalysis", {
        code: code
      }, function (res, error) {
        console.log(res); 
        var userType = app.globalData.userType; console.log(userType)
        if (res.data.success) {
          if (userType == 'driver') {
            switch (res.data.data.type){
              case 'shop':
                wx.redirectTo({
                  url: '/pages/driver/currentOrder?id=' + res.data.data.orderId + '&shop=' + res.data.data.shopId + '&guid=' + code
                });
              break;
            }
          }
        } else {
          wx.showModal({
            content:"未有关联业务",
            success: function (res) {
              if (res.confirm) {

              } else if (res.cancel) {

              }
            }
          })
        }
      });
    }
  });
}
function html_encode(str)
{
  if (str == "" || str == undefined || typeof str != "string") {
    return str;
  } else {
    var s = "";
    if(str.length == 0) return "";
    s = str.replace(/&/g,"&");
    s = s.replace(/</g,"<");
    s = s.replace(/>/g,">");
    s = s.replace(/ /g," ");
    s = s.replace(/\'/g,"'");
    s = s.replace(/\"/g,'"');
    return s;
  }
}
function html_decode(str) {
  if (str == "" || str == undefined || typeof str != "string") {
    return str;
  } else {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'").replace(/&#34;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/<br>/g, "\n");
    return s;
  };
}
function arrayDeleteWithIndex(arr,index,num){
  arr.splice(index, num);
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == "" || typeof (arr[i]) == "undefined") {
      arr.splice(i, 1);
      i = i - 1;
    }
  }
  return arr;
}
function arrayDeleteEmpty(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == "" || typeof (arr[i]) == "undefined") {
      arr.splice(i, 1);
      i = i - 1;
    }
  }
  return arr;
}
function arrayDeleteItem(arr,item) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == item) {
      arr.splice(i, 1);
      i = i - 1;
    }
  }
  return arr;
}

function imagesArray(arr,server) {
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] != "" && typeof (arr[i]) != "undefined") {
      arr[i] = server + arr[i];
      newArr.push(arr[i])
    }
  }
  return newArr;
}
function getRoleList(that, CO_ID, role_default, roles) {
  var currentCompany = '', currentRoles = [], isMoreCompany = false, isCoAdmin = false, isDriver = false;
  if(typeof roles == 'object'){
  for (var i = 0; i < roles.length;i++) {
    if (roles[i].CO_ID == CO_ID){
      currentCompany = roles[i].CO_NAME||'无企业';
      var _currentRoles = {};
      if (roles[i].role == 'schedule') {
        _currentRoles = { 'name': '客服跟单员', 'CO_ID': roles[i].CO_ID, 'role': 'schedule' }
      }
      if (roles[i].role == 'driver') {
        _currentRoles = { 'name': '司机', 'CO_ID': roles[i].CO_ID, 'role': 'driver' }
        isDriver = true;
      }
      if (roles[i].role == 'fleet') {
        _currentRoles = { 'name': '运力调度员', 'CO_ID': roles[i].CO_ID, 'role': 'fleet' }
      }
      if (roles[i].role == 'finance') {
        _currentRoles = { 'name': '财务结算员', 'CO_ID': roles[i].CO_ID, 'role': 'finance' }
      }
      if (roles[i].role == 'admin') {
        _currentRoles = { 'name': '企业管理员', 'CO_ID': roles[i].CO_ID, 'role': 'admin' }
        isCoAdmin = true;
      } 
      if (roles[i].role == 'operation') {
        _currentRoles = { 'name': '运营管理员', 'CO_ID': roles[i].CO_ID, 'role': 'operation' }
      }
      if (roles[i].role == role_default){
        _currentRoles.default = true;
      }else{
        _currentRoles.default = false;
      }
      currentRoles.push(_currentRoles);
    }else{
      isMoreCompany = true;
    }
  }
}
  console.log({
    currentCompany: currentCompany,
    currentRoles: currentRoles,
    isMoreCompany: isMoreCompany
  })
  that.setData({
      roles: {
        currentCompany: currentCompany,
        currentRoles: currentRoles,
        isMoreCompany: isMoreCompany,
        isCoAdmin: isCoAdmin,
        isDriver: isDriver
      }
  })
  try {
    wx.setStorageSync('CO_NAME', currentCompany)
  } catch (e) { }
}
function getCloseDeliveryROle(roleData,CO_ID){
   var hasRole = false;
   for(var i=0;i<roleData.length;i++){
     if(roleData[i].CO_ID == CO_ID && (roleData[i].role == 'operation' || roleData[i].role == 'admin')){
      hasRole = true;
     }
   }
   return hasRole;
}
var roleList = [
  {'role':'schedule','name':'客服跟单员'},
  {'role':'driver','name':'司机'},
  {'role':'fleet','name':'运力调度员'},
  {'role':'finance','name':'财务结算员'},
  {'role':'operation','name':'运营管理员'},
  {'role':'admin','name':'企业管理员'}
]
function roleToName(role){
  if (role == 'schedule') {
    return '客服跟单员';
  }
  if (role == 'driver') {
    return '司机';
  }
  if (role == 'fleet') {
    return '运力调度员';
  }
  if (role == 'finance') {
    return '财务结算员';
  }
  if (role == 'admin') {
    return '企业管理员';
  }
  if (role == 'operation') {
    return '运营管理员';
  }
}
function getCompanyList(that, CO_ID, roles){
  var companyList = [];
  for (var i = 0; i < roles.length; i++) {
    if (companyList.length == 0){
      companyList.push({ 'CO_NAME': roles[i].CO_NAME, 'CO_ID': roles[i].CO_ID, 'checked': (roles[i].CO_ID == CO_ID ? true : false) });
    }else{
      var isHas = false;
      for (var j = 0; j < companyList.length; j++) {
        if (roles[i].CO_ID == companyList[j].CO_ID){
          isHas = true;
        }
      }
      if (!isHas){
        companyList.push({ 'CO_NAME': roles[i].CO_NAME, 'CO_ID': roles[i].CO_ID, 'checked': (roles[i].CO_ID == CO_ID ? true : false) });
      }
    }
  }
  that.setData({
    companyList: companyList
  })
}
function registerDriver(app, that){
  wx.showModal({
    title: '温馨提示',
    content: '确认要注册司机会员吗？',
    success: function (res) {
      if (res.confirm) {
        postData("/wechat/passport/driverRegister", {
          'fromOtherRole': 'true',
          'CO_ID': app.globalData.CO_ID,
          'user_id': app.globalData.user_id,
          'name': app.globalData.truename,
          'phone': app.globalData.mobile,
          'openid': app.globalData.openid,
          'unionid': app.globalData.unionid
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            wx.showModal({
              title: '温馨提示',
              content: '注册成功，需要重新加载权限',
              success: function (res) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            });
          } else {
            wx.showToast({
              title: "注册失败",
              image: '/images/wrong.png',
              duration: 3000
            });
          }
        });
      }
    }
  })
}
function registerCompany(){
  wx.showModal({
    title: '温馨提示',
    content: '请联系客服开通企业账户',
    success: function (res) {
      if (res.confirm) {
        // wx.redirectTo({
        //   url: '/pages/auth/enterpriseReg'
        // })
      }
    }
  })
}
function pricePriorityMode(index) {
  if (String(index).length > 2) {
    if (index == 'auction_time') {//竞价时间顺序
      return 0;
    }
    if (index == 'user_select') {//人工选择
      return 1;
    }
  } else {
    if (index == 0) {//竞价时间顺序
      return 'auction_time';
    }
    if (index == 1) {//人工选择
      return 'user_select';
    }
  }
}
var goodsUnit = ['框', '箱', '吨', '公斤', '板', '包'];
var vehicleTag = ['常用', '备用', '冷藏车', '回框', '仅白班'];
function toFixedPlus(n,d) {
  if (d <= 0) {
      return n;
  } else {
      var _n = String(n).split('.');
      var new_n = _n[0]+'.'+String((_n[1]||0)+'000000000000').substr(0,d)
      return Number(new_n);
  }
}
function newguid() {
  function S4() {
     return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  }
  return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4());
}
/////////////////////////////////////////////
module.exports = {
  formatTime: formatTime,
  dateformat: dateformat,
  getDateStr: getDateStr,
  dateObjectformat: dateObjectformat,
  getData: getData,
  postData: postData,
  putData: putData,
  deleteData: deleteData,
  getData2: getData2,
  postData2: postData2,
  putData2: putData2,
  deleteData2: deleteData2,
  speechRecognition: speechRecognition,
  setPointAttr: setPointAttr,
  hourToTime: hourToTime,
  vehicleTrace: vehicleTrace,
  vehicleTraceWithIotbox: vehicleTraceWithIotbox,
  gpsTransform: gpsTransform,
  getGpsDisance: getGpsDisance,
  driverScan: driverScan,
  html_decode: html_decode,
  html_encode:html_encode,
  arrayDeleteWithIndex: arrayDeleteWithIndex,
  arrayDeleteEmpty: arrayDeleteEmpty,
  arrayDeleteItem: arrayDeleteItem,
  imagesArray: imagesArray,
  getRoleList: getRoleList,
  roleToName: roleToName,
  roleList:roleList,
  getCompanyList: getCompanyList,
  getCloseDeliveryROle:getCloseDeliveryROle,
  registerDriver: registerDriver,
  registerCompany: registerCompany,
  goodsUnit: goodsUnit,
  vehicleTag: vehicleTag,
  pricePriorityMode: pricePriorityMode,
  toFixedPlus:toFixedPlus,
  newguid:newguid
}